package command

import (
	"gitee.com/moyrn/sa/store"
	"github.com/spf13/cobra"
	"os"
)

var runCmd = &cobra.Command{
	Use:   "run",
	Long:  "执行程序",
	Short: "执行程序",
	Run: func(cmd *cobra.Command, args []string) {
		if e == nil {
			store.Log.Panic("engine is not initialize")
		}

		if reCreate {
			store.Log.Info("reCreate", "删除数据库文件", dbName)
			if err := os.Remove(dbName); err != nil {
				store.Log.Panic("reCreate", dbName, err)
			}
			os.Exit(0)
		}
		if resetLoaded {
			store.Log.Info("resetLoaded", "重置未完成任务")
			if err := e.Store.Loaded2Unload(); err != nil {
				store.Log.Panic("resetLoaded", err)
				return
			}
		}

		for _, s := range seeds {
			if err := e.SetNewTask(&s); err != nil {
				store.Log.Info("SetNewTask", "maybe existed", err)
			}
		}

		e.Run()
	},
}

func init() {
	runCmd.Flags().Int64VarP(&tick, "tick", "t", 1000, "请求间隔时间(单位:ms)")
	runCmd.Flags().BoolVarP(&reCreate, "reCreate", "c", false, "重新创建数据库文件")
	runCmd.Flags().BoolVarP(&resetLoaded, "resetLoaded", "l", true, "重新执行未完成状态的任务")
}
